package com.znjc.iot.task;

import cn.hutool.core.thread.ThreadUtil;
import com.znjc.iot.domain.IotDataCheck;
import com.znjc.iot.domain.IotSerial;
import com.znjc.iot.exception.SendDataToSerialPortFailure;
import com.znjc.iot.exception.SerialPortOutputStreamCloseFailure;
import com.znjc.iot.serial.SerialPortHandler;
import com.znjc.iot.serial.SerialPortUtil;
import com.znjc.iot.util.CRC16M;
import com.znjc.iot.util.CRC_16;
import com.znjc.iot.util.CommonUtil;
import com.znjc.iot.util.DataUtil;
import com.znjc.iot.websocket.CustomizedWebSocketClient;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * 设备数据采集定时任务
 *
 * @author gzj
 */
@Data
@AllArgsConstructor
@Slf4j
public class CollectDataTask implements Runnable {

    private final Long serialId;

    private final CustomizedWebSocketClient customizedWebSocketClient;

    private final IotSerial serial;

    private final List<IotDataCheck> dataChecks;

    @Override
    public void run() {
        SerialPortUtil serialPortUtil = CommonUtil.getSerialPortUtils(serial);
        if (null != serialPortUtil) {
            //采集数据
            dataChecks.forEach(dataCheck -> {
                byte[] byteMsg = CRC_16.getSendBuf(dataCheck.getCommand().replaceAll(" ",""));
                log.info("读数据下发："+DataUtil.printHexString(byteMsg));
                ThreadUtil.execAsync(() -> {
                    try {
                        serialPortUtil.sendData(byteMsg);
                    } catch (RuntimeException e) {
                        throw new RuntimeException(e);
                    } catch (SendDataToSerialPortFailure e) {
                        throw new RuntimeException(e);
                    } catch (SerialPortOutputStreamCloseFailure e) {
                        throw new RuntimeException(e);
                    }
                });
            });
        }
    }
}
